<template>
<block>
	<!-- <view class="text-center margin-bottom">
		<view class="text-xsl margin-top without">
			<image class="margin-top-sm" src="/static/public/img/shopping-cart.jpg"></image>
		</view>
	  购物车为空<br/>
	  赶快去逛逛, 购买心仪的商品吧
	  <navigator hover-class="none" url="/pages/goods/goods-list/index">
	    <button class="cu-btn bg-black margin-top">去逛逛</button>
		<button plain="trur" style="color: #F9D7EA; border-color: #9000FF;width: 60px;">去逛逛</button>
	  </navigator>
	</view> -->
	<view class="cart-empty-001">
		<!-- <view class="iconcart"></view> -->
		<view class="text-xsl margin-top">
			<image class="margin-top-sm" src="/static/public/img/shopping-cart.jpg"></image>
		</view>
		<view class="namecart">购物车为空</view>
		<view class="desccart">赶紧去逛逛，购买心仪的商品吧</view>
		<a href="" class="btncart">去逛逛</a>
	</view>
<!-- <view class="cu-bar bg-white fixed" style="min-height: 80rpx;font-weight: 300;">
  <view class="grid col-3 response text-center text-gray">
    <view><text class="cuIcon-selection margin-right-xs"></text>100%正品保证</view>
    <view><text class="cuIcon-discover margin-right-xs"></text>精挑细选</view>
    <view><text class="cuIcon-squarecheck margin-right-xs"></text>售后无忧</view>
  </view>
</view> -->
	<!-- <view class="cu-bar bg-white solid-bottom solid-top fixed" style="margin-top:80rpx; min-height: 80rpx;box-shadow:none;">
	  <view class="action">
		共{{shoppingCartData.length}}件宝贝
	  </view>
	  <view class="action">
		<button class="cu-btn line-gray sm" @tap="operationFun">{{operation ? '管理' : '完成'}}</button>
	  </view>
	</view> -->
<!-- 	<view class="bg-white" style="margin-top:160rpx;margin-bottom:100rpx;padding-top:40rpx;">
	  <checkbox-group @change="checkboxChange">
		<view class="cu-card article no-card solid-bottom">
		  <view class="cu-item padding-top-xs" v-for="(item,index) in (shoppingCartData)" :key="index">
			<view class="flex align-center">
			  <checkbox class="blue round margin-left" :value="item.id" :disabled="(item.quantity > item.goodsSpu.stock || !item.goodsSpu) && operation" :checked="item.checked"></checkbox>
			  <navigator hover-class="none" style="width:100%" :url="'/pages/goods/goods-detail/index?id='+(item.spuId)">
				<view class="content">
				  <image :src="item.goodsSpu.picUrls[0] ? item.goodsSpu.picUrls[0] : '/public/img/no_pic.png'" mode="aspectFill" class="row-img margin-top-xs"></image>
				  <view class="desc row-info">
					<view class="text-black margin-top-sm overflow-2">{{item.goodsSpu.name}}</view>
					<view class="text-gray text-sm margin-top-xs cu-tag round" catchtap @tap="changeSpecs" :data-spuid="item.goodsSpu.id" :data-index="index" v-if="item.goodsSpu.specType == '1'">
					  <text class="overflow-1"></text>
					  <text class="cuIcon-unfold"></text>
					</view>
					<view :class="'text-'+(item.quantity > item.goodsSpu.stock ? 'red' : 'gray')+' margin-top-sm text-right text-sm'">库存{{item.goodsSpu.stock}}</view>
					<view v-if="item.goodsSpu">
					  <view class="text-red margin-top-sm" v-if="(item.addPrice-item.goodsSpu.salesPrice) > 0">
						比加入时降
						<view class="text-price display-ib">{{numberUtil.numberFormat(item.addPrice-item.goodsSpu.salesPrice,2)}}</view>
					  </view>
					  <view class="flex">
						<view class="flex-sub">
						  <view class="text-price text-bold text-blue text-xl margin-top-sm">{{item.goodsSpu.salesPrice}}</view>
						</view>
						<view class="flex-sub margin-top-sm" catchtap>
						  <base-stepper :stNum="item.quantity" :min="1" :max="item.goodsSpu.stock" @numChange="cartNumChang" :data-index="index"/>
						</view>
					  </view>
					</view>
					<view v-if="(!item.goodsSpu)" class="margin-top-sm">
					  <view class="text-red">请重新选择规格</view>
					</view>
				  </view>
				</view>
			  </navigator>
			</view>
		  </view>
		</view>
	  </checkbox-group> -->
	  <!-- 失效商品 -->
	  <!-- <view class="cu-bar bg-white solid-bottom margin-top" v-if="shoppingCartDataInvalid.length > 0">
		<view class="action">
		  失效宝贝{{shoppingCartDataInvalid.length}}件
		</view>
		<view class="action">
		  <button class="cu-btn line-blue round" @tap="clearInvalid">清空失效宝贝</button>
		</view>
	  </view>
	  <view class="cu-card article no-card">
		  <view class="cu-item" v-for="(item,index) in (shoppingCartDataInvalid)" :key="index">
			<view class="flex align-center">
			  <navigator hover-class="none" style="width:100%" :url="'/pages/goods/goods-detail/index?id='+(item.spuId)">
				<view class="content">
				  <image :src="item.goodsSpu.picUrls[0] ? item.goodsSpu.picUrls[0] : '/public/img/no_pic.png'" mode="aspectFill" class="row-img margin-top-xs"></image>
				  <view class="desc row-info">
					<view class="text-black margin-top-sm overflow-2">{{item.goodsSpu.name}}</view>
					<view class="text-sm margin-top-lg text-blue">
					  已下架
					</view>
				  </view>
				</view>
			  </navigator>
			</view>
		  </view>
	  </view>
	  <view :class="'cu-load bg-gray '+(loadmore?'loading':'')"></view>
	  <view class="text-center margin-bottom" v-if="shoppingCartData.length <= 0 && !loadmore">
		<view class="text-xsl margin-top without">
				<image class="margin-top-sm" src="/static/public/img/shopping-cart.jpg"></image>
			</view>
		购物车空空如也~
		<navigator hover-class="none" url="/pages/goods/goods-list/index">
		  <button class="cu-btn bg-black margin-top">去逛逛</button>
		</navigator>
	  </view>
	  <ad :unit-id="config.adBannerID" v-if="config.adEnable"></ad>
	  <view class="cu-bar justify-center bg-white margin-top-sm">
		<view class="action text-blue text-bold">
		  <text class="cuIcon-move"></text> <text class="cuIcon-appreciate"></text>为您推荐 <text class="cuIcon-move"></text>
		</view>
	  </view>
	  <goods-card :goodsList="goodsListRecom"/>
	</view>
	<view class="cu-bar bg-white tabbar border shop foot">
	  <view class="flex align-center">
		<checkbox-group @change="checkboxAllChange">
		  <checkbox class="blue round margin-left" value="all" :checked="isAllSelect"></checkbox>
		</checkbox-group>
		<view class="text-lg margin-left-xs">全选</view>
	  </view>
	  <view class="action bar-rt" v-if="operation">
		<text class="text-xs text-bold">合计：</text>
		<text class="text-xl text-bold text-price text-blue margin-right-sm">{{settlePrice}}</text>
		<button class="cu-btn shadow-blur margin-left-sm settle-bt" :disabled="selectValue.length <= 0" type="" @tap="orderConfirm">
		  <text class="text-white">结算{{selectValue.length > 0 ? '('+selectValue.length+')' : ''}}</text>
		</button>
	  </view>
	  <view class="action bar-rt" v-if="(!operation)">
		<button class="cu-btn shadow-blur collection" :disabled="selectValue.length <= 0" @tap="userCollectAdd"><text class="text-white">移入收藏夹</text></button>
		<button class="cu-btn shadow-blur margin-left-sm delete" :disabled="selectValue.length <= 0" @tap="shoppingCartDel"><text class="text-white">删除</text></button>
	  </view>
	</view> -->
</block>
</template>
<script module="numberUtil" lang="wxs" src="../../utils/numberUtil.wxs"></script>
<script>
import baseStepper from "@/components/base-stepper/index";
import goodsCard from "@/components/goods-card/index";
const app = getApp();
export default {
                    components: {
                      baseStepper,
                      goodsCard
                    },
                    data() {
            return {
              config: app.globalData.config,

              page: {
                current: 1,
                size: 50,
                ascs: '',
                //升序字段
                descs: 'create_time'
              },

              parameter: {},
              loadmore: true,
              operation: true,
              shoppingCartData: [],
              shoppingCartDataInvalid: [],
              isAllSelect: false,

              //全选
              selectValue: [],

              settlePrice: 0,

              //结算金额
              goodsSpu: [],

              shoppingCartSelect: [],
              goodsListRecom: ""
            };
        }, 
onShow() {
  //更新tabbar购物车数量
  uni.setTabBarBadge({
    index: 2,
    text: app.globalData.shoppingCartCount + ''
  });
  app.globalData.initPage().then(res => {
    this.shoppingCartPage();
  });
}, 
onLoad: function () {
  app.globalData.initPage().then(res => {
    this.goodsRecom();
  });
}, 
methods: {
    //管理按键事件
    operationFun() {
      this.setData({
        operation: !this.operation
      });
      this.checkboxHandle(this.selectValue);
    },

    //加载数据
    shoppingCartPage() {
      app.globalData.api.shoppingCartPage(this.page).then(res => {
        //更新购物车数量
        app.globalData.shoppingCartCount = res.data.total + '';
        uni.setTabBarBadge({
          index: 2,
          text: app.globalData.shoppingCartCount + ''
        });
        let shoppingCartData = []; //过滤出失效商品

        let shoppingCartDataInvalid = [];
        res.data.records.forEach(function (shoppingCart, index) {
          if (!shoppingCart.goodsSpu || shoppingCart.goodsSpu.shelf == '0') {
            //下架或删除了
            shoppingCartDataInvalid.push(shoppingCart);
          } else {
            shoppingCartData.push(shoppingCart);
          }
        });
        this.setData({
          shoppingCartData: shoppingCartData,
          shoppingCartDataInvalid: shoppingCartDataInvalid,
          loadmore: false
        });
        let selectValue = this.selectValue;

        if (selectValue.length > 0) {
          this.checkboxHandle(selectValue);
        }
      });
    },

    //推荐商品
    goodsRecom() {
      app.globalData.api.goodsPage({
        searchCount: false,
        current: 1,
        size: 4,
        descs: 'create_time'
      }).then(res => {
        let goodsListRecom = res.data.records;
        this.setData({
          goodsListRecom: goodsListRecom
        });
      });
    },

    //数量变化
    cartNumChang(e) {
      let index = e.target.dataset.index;
      let shoppingCart = this.shoppingCartData[index];
      let quantity = Number(e.detail);
      this.shoppingCartData[index].quantity=quantity
      this.shoppingCartEdit({
        id: shoppingCart.id,
        quantity: quantity
      });
      this.countSelect();
    },

    shoppingCartEdit(parm) {
      app.globalData.api.shoppingCartEdit(parm);
    },

    //收藏
    userCollectAdd() {},

    shoppingCartDel() {
      let selectValue = this.selectValue;
      let that = this;

      if (selectValue.length > 0) {
        uni.showModal({
          content: '确认将这' + selectValue.length + '个宝贝删除',
          cancelText: '我再想想',
          confirmColor: '#ff0000',

          success(res) {
            if (res.confirm) {
              app.globalData.api.shoppingCartDel(selectValue).then(res => {
                that.setData({
                  selectValue: [],
                  isAllSelect: false,
                  settlePrice: 0
                });
                that.shoppingCartPage();
              });
            }
          }

        });
      }
    },

    clearInvalid() {
      let selectValue = [];
      let that = this;
      this.shoppingCartDataInvalid.forEach(function (shoppingCart, index) {
        selectValue.push(shoppingCart.id);
      });
      uni.showModal({
        content: '确认清空失效的宝贝吗',
        cancelText: '我再想想',
        confirmColor: '#ff0000',

        success(res) {
          if (res.confirm) {
            app.globalData.api.shoppingCartDel(selectValue).then(res => {
              that.setData({
                shoppingCartDataInvalid: []
              });
            });
          }
        }

      });
    },

    checkboxHandle(selectValue) {
      let that = this;
      let shoppingCartData = this.shoppingCartData;
      let isAllSelect = false;

      if (shoppingCartData.length == selectValue.length) {
        isAllSelect = true;
      }

      if (selectValue.length > 0) {
        let shoppingCartIds = [];
        shoppingCartData.forEach(function (shoppingCart, index) {
          shoppingCartIds.push(shoppingCart.id);
          let selectValueIndex = selectValue.indexOf(shoppingCart.id);

          if (selectValueIndex > -1) {
            if (!that.data.operation) {
              shoppingCart.checked = true;
            } else {
              //如果是购买操作，需过滤不符商品
              if (shoppingCart.goodsSpu && shoppingCart.quantity <= shoppingCart.goodsSpu.stock) {
                shoppingCart.checked = true;
              } else {
                shoppingCart.checked = false;
                selectValue.splice(selectValueIndex, 1);
              }
            }
          } else {
            shoppingCart.checked = false;
          }
        });
        selectValue.forEach(function (obj, index) {
          if (shoppingCartIds.indexOf(obj) <= -1) {
            selectValue.splice(index, 1);
          }
        });
      } else {
        shoppingCartData.forEach(function (shoppingCart, index) {
          shoppingCart.checked = false;
        });
      }

      this.setData({
        shoppingCartData: shoppingCartData,
        isAllSelect: isAllSelect,
        selectValue: selectValue
      });
      this.countSelect();
    },

    checkboxChange: function (e) {
      this.checkboxHandle(e.detail.value);
    },

    checkboxAllChange(e) {
      var value = e.detail.value;

      if (value.length > 0) {
        this.setAllSelectValue(true);
      } else {
        this.setAllSelectValue(false);
      }
    },

    setAllSelectValue(status) {
      let shoppingCartData = this.shoppingCartData;
      let selectValue = [];
      let that = this;

      if (shoppingCartData.length > 0) {
        if (status) {
          shoppingCartData.forEach(function (shoppingCart, index) {
            if (!that.data.operation) {
              selectValue.push(shoppingCart.id);
            } else {
              //如果是购买操作，需过滤不符商品
              if (shoppingCart.goodsSpu && shoppingCart.quantity <= shoppingCart.goodsSpu.stock) {
                selectValue.push(shoppingCart.id);
              }
            }
          });
        }

        this.checkboxHandle(selectValue);
      }
    },

    //计算结算值
    countSelect() {
      let selectValue = this.selectValue;
      let settlePrice = 0;

      if (selectValue.length <= 0) {
        this.setData({
          settlePrice: settlePrice
        });
      } else {
        this.shoppingCartData.forEach(function (shoppingCart, index) {
          if (selectValue.indexOf(shoppingCart.id) > -1 && shoppingCart.goodsSpu && shoppingCart.quantity <= shoppingCart.goodsSpu.stock) {
            settlePrice = Number(settlePrice) + Number(shoppingCart.quantity) * Number(shoppingCart.goodsSpu.salesPrice);
          }
        });
        this.setData({
          settlePrice: settlePrice.toFixed(2)
        });
      }
    },

    //更换规格
    changeSpecs(e) {},

    goodsGet(id) {
      app.globalData.api.goodsGet(id).then(res => {
        let goodsSpu = res.data;
        this.setData({
          goodsSpu: goodsSpu
        });
      });
    },

    operateCartEvent() {
      this.shoppingCartPage();
    },

    //结算
    orderConfirm() {
      let params = [];
      let shoppingCartData = this.shoppingCartData;
      shoppingCartData.forEach(function (shoppingCart, index) {
        if (shoppingCart.checked && shoppingCart.goodsSpu && shoppingCart.goodsSpu && shoppingCart.goodsSpu.shelf == '1' && shoppingCart.quantity <= shoppingCart.goodsSpu.stock) {
          let param = {
            spuId: shoppingCart.spuId,
            quantity: shoppingCart.quantity,
            salesPrice: shoppingCart.goodsSpu.salesPrice,
            spuName: shoppingCart.goodsSpu.name,
            picUrl: shoppingCart.goodsSpu.picUrls ? shoppingCart.goodsSpu.picUrls[0] : ''
          };
          params.push(param);
        }
      });
      /* 把参数信息异步存储到缓存当中 */

      uni.setStorage({
        key: 'param-orderConfirm',
        data: params
      });
      uni.navigateTo({
        url: '/pages/order/order-confirm/index'
      });
    }
}
                };
</script>
<style >
.bar-rt{
  width: 480rpx!important;
  text-align: right!important;
  margin-right: 10rpx!important
}
.settle-bt{
  background-color: #2967ff !important;
  font-weight:300;
  width:220rpx;
}
.row-img{
  width: 30%!important;
  border-radius: 10rpx
}
.row-info{
  display: block!important;
  width: 60%;
}
.row-specs{
  width: 200px;
}
.cu-tag {
  white-space: unset!important
}
.without {
  margin: auto;
}
.without image {
  padding-top: 50rpx;
  width: 360rpx;
  height: 305rpx;
}
.collection{
  background-color: #2d2d2f !important;
  font-weight:300;
  width:220rpx;
}
.delete{
  background-color: #2967ff !important;
  font-weight:300;
  width:220rpx;
}
</style>